/*
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.tsunami.plugins.detectors.rce.torchserve;

import static com.google.common.truth.Truth.assertThat;
import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort;

import com.google.tsunami.plugin.payload.testing.PayloadTestHelper;
import com.google.tsunami.proto.NetworkService;
import com.google.tsunami.proto.Software;
import com.google.tsunami.proto.TransportProtocol;
import javax.inject.Inject;
import okhttp3.mockwebserver.MockResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TorchServeExploiterTestWithCallback
    extends TorchServeManagementApiTestBaseWithCallbackServer {
  @Inject private TorchServeExploiter exploiter;
  NetworkService service;

  public void onTestExecution() {
    setUpNetworkService();
    setUpMockServices();
  }

  private void setUpNetworkService() {
    service =
        NetworkService.newBuilder()
            .setNetworkEndpoint(
                forHostnameAndPort(mockTorchServe.getHostName(), mockTorchServe.getPort()))
            .setTransportProtocol(TransportProtocol.TCP)
            .setSoftware(Software.newBuilder().setName("torchserve"))
            .setServiceName("http")
            .build();
  }

  public void setUpMockServices() {
    mockTorchServe.enqueue(
        new MockResponse()
            .setResponseCode(200)
            .setBody(
                "{\n"
                    + "  \"openapi\": \"3.0.1\",\n"
                    + "  \"info\": {\n"
                    + "    \"title\": \"TorchServe APIs\",\n"
                    + "    \"description\": \"TorchServe is a flexible and easy to use tool for"
                    + " serving deep learning models\",\n"
                    + "    \"version\": \"0.8.1\"\n"
                    + "  },\n"
                    + "  \"paths\": {\n"
                    + "    \"/models\": {\n"
                    + "      \"post\": {\n"
                    + "        \"description\": \"Register a new model in TorchServe.\",\n"
                    + "        \"operationId\": \"registerModel\"\n"
                    + "     }\n"
                    + "    }\n"
                    + "  }\n"
                    + "}"));

    // Mocking the response for listing models - assuming an empty list for simplicity
    mockTorchServe.enqueue(new MockResponse().setResponseCode(200).setBody("{\"models\": []}"));

    // Mocking the response for removeModelByUrl
    mockTorchServe.enqueue(new MockResponse().setResponseCode(200).setBody("{\"models\": []}"));

    // Mocking the response for model registration
    mockTorchServe.enqueue(
        new MockResponse()
            .setResponseCode(200)
            .setBody(
                "{\n"
                    + "  \"status\": \"Model \\\"squeezenet1_1\\\" Version: 1.0 registered with 1"
                    + " initial workers\"\n"
                    + "}"));
  }

  @Test
  public void details_isServiceVulnerableReturnsNullIfCallbackNotTriggered() throws Exception {
    mockCallbackServer.enqueue(PayloadTestHelper.generateMockUnsuccessfulCallbackResponse());

    exploiter.details.exploitationMode = TorchServeExploiter.ExploitationMode.SSRF;
    assertThat(exploiter.isServiceVulnerable(service)).isNull();
  }

  @Test
  public void detect_isServiceVulnerable_returnsDetailsIfCallbackTriggered() throws Exception {
    mockCallbackServer.enqueue(PayloadTestHelper.generateMockSuccessfulCallbackResponse());

    exploiter.details.exploitationMode = TorchServeExploiter.ExploitationMode.SSRF;
    assertThat(exploiter.isServiceVulnerable(service)).isNotNull();
  }
}
